<?php

namespace app\api\controller;

use app\admin\model\Wxframeconf;
use app\admin\model\Wxcomponentconf;
use app\admin\model\Article;
use app\admin\model\Villages;
use app\admin\model\Operator;
use app\admin\model\Member;
use app\admin\model\Image;
use app\admin\model\Product;
use app\admin\model\Povertyproject;
use app\admin\model\Activity;
use app\admin\model\Communitydynamics;
use app\admin\service\Dynamic as DynamicService;

use think\Request;

/**
 * 首页
 */
class HomeFrame extends BaseController
{

    protected $userId;

    /**
     * 自定义首页
     */
    public function getHomeFrame()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        $this->userId = $param->userId;
        $where = [
            'townId' => $param->townId
        ];
        $fields = 'id, name, typeId, layoutType, layoutContent, showLineCount, showCount, onlyShowImg, backgroudColor, fontColor, combinationImg, sorting';
        $data = Wxframeconf::where($where)->field($fields)->order('sorting ASC, createDate ASC')->select();
        if(!$data){
            // 没有添加首页内容，则取默认的
            $defaultWhere = [
                'cityId' => 0,
                'xianId' => 0
            ];
            $data = Wxframeconf::where($defaultWhere)->field($fields)->order('sorting ASC, createDate ASC')->select();
        }

        if($data){
            foreach ($data as $item) {
                switch ($item['typeId']) {
                    case 1:
                        // 轮播图
                        $field = 'displayName, imgUrl, linkType, linkCateId, linkId, sorting';
                        $component = Wxcomponentconf::where('frameId', $item['id'])->field($field)->order('sorting ASC, createDate DESC')->select();
                        if($component){
                            $item['contentList'] = $component;
                        }
                        break;
                    case 2:
                        // 组合图
                        $combinationImg = json_decode($item['combinationImg'], true);
                        if($combinationImg){
                            /*$combinationImg['linkType'] = $combinationImg['imgLinks'];
                            unset($combinationImg['imgLinks']);
                            $item['combinationImg'] = $combinationImg;*/
                            $item['groupType'] = $combinationImg['groupType'];
                            $contentList = [];
                            foreach ($combinationImg['imgUrls'] as $key => $value) {
                                $contentList[] = [
                                    'displayName' => isset($combinationImg['displayNames'][$key]) ? $combinationImg['displayNames'][$key] : '',
                                    'imgUrl' => isset($combinationImg['imgUrls'][$key]) ? $combinationImg['imgUrls'][$key] : '',
                                    'linkType' => isset($combinationImg['linkTypes'][$key]) ? $combinationImg['linkTypes'][$key] : '',
                                    'linkCateId' => isset($combinationImg['linkCateIds'][$key]) ? $combinationImg['linkCateIds'][$key] : '',
                                    'linkId' => isset($combinationImg['linkIds'][$key]) ? $combinationImg['linkIds'][$key] : '',
                                ];
                            }
                            $item['contentList'] = $contentList;
                            unset($item['combinationImg']);
                        }
                        break;
                    case 3:
                        // 推荐内容/列表
                        if($item['layoutContent']){
                            $item['layoutContentName'] = show_link_name($item['layoutContent']);
                            $item['linkType'] = $item['layoutContent'];
                            $item['contentList'] = $this->getCustomList($item, $where);
                        }
                        break;
                    case 4:
                        // 视频
                        $field = 'imgUrl, videoUrl';
                        $component = Wxcomponentconf::where('frameId', $item['id'])->field($field)->find();
                        if($component){
                            $item['imgUrl'] = $component['imgUrl'];
                            $item['videoUrl'] = $component['videoUrl'];
                        }else{
                            $item['imgUrl'] = '';
                            $item['videoUrl'] = '';
                        }
                        break;
                    case 6:
                        // 自适应图片
                        $field = 'displayName, imgUrl, linkType, linkCateId, linkId, sorting';
                        $component = Wxcomponentconf::where('frameId', $item['id'])->field($field)->order('sorting ASC, createDate DESC')->select();
                        if($component){
                            $item['contentList'] = $component;
                        }
                        break;
                    case 7:
                        // 按钮导航
                        $field = 'displayName, imgUrl, linkType, linkCateId, linkId, sorting';
                        $component = Wxcomponentconf::where('frameId', $item['id'])->field($field)->order('sorting ASC, createDate DESC')->select();
                        if($component){
                            $item['contentList'] = $component;
                        }
                        break;
                    default: break;
                }
            }
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 获取自定义列表内容
     */
    public function getCustomList($config, $where)
    {
        if(!$config['layoutContent']){
            return [];
        }

        $layoutType = $config['layoutType'];
        $type = $config['layoutContent'];
        $limit = $config['showCount'];
        $data = [];
        switch ($type) {
            case 1:
                // 头条
                $where['type'] = 'toutiao';
                $data = $this->getArticles($where, $limit, $layoutType);
                break;
            case 2:
                // 村子
                $data = $this->getVillages($where, $limit, $layoutType);
                break;
            case 3:
                // 村民
                $data = $this->getMembers($where, $limit, $layoutType);
                break;
            case 4:
                // 村里事
                $where['type'] = 'village';
                $data = $this->getArticles($where, $limit, $layoutType);
                break;
            case 5:
                // 乡镇机关
                $data = $this->getInstitutions($where, $limit, $layoutType);
                break;
            case 6:
                // 农事服务
                $data = $this->getFarmings($where, $limit, $layoutType);
                break;
            /*case 7:
                // 本地特色
                $data = $this->getFeaturecolumns($where, $limit, $layoutType);
                break;*/
            case 8:
                // 特色专题
                $data = $this->getFeatures($where, $limit, $layoutType);
                break;
            case 9:
                // 通知
                $where['type'] = 'notice';
                $data = $this->getArticles($where, $limit, $layoutType);
                break;
            case 10:
                // 党建要闻
                $where['type'] = 'party';
                $data = $this->getArticles($where, $limit, $layoutType);
                break;
            case 11:
                // 微课堂
                $data = $this->getMicroclassrooms($where, $limit, $layoutType);
                break;
            case 12:
                // 在线考试
                $data = $this->getOnlineexams($where, $limit, $layoutType);
                break;
            case 13:
                // 会议
                $data = $this->getMeetings($where, $limit, $layoutType);
                break;
            case 14:
                // 调研
                $data = $this->getResearchs($where, $limit, $layoutType);
                break;
            case 15:
                // 活动
                $data = $this->getActivity($where, $limit, $layoutType);
                break;
            case 16:
                // 扶贫动态
                $where['type'] = 'povertydynamic';
                $data = $this->getArticles($where, $limit, $layoutType);
                break;
            case 17:
                // 扶贫项目
                $projectWhere = [];
                foreach ($where as $key => $val) {
                    $projectWhere['a.' . $key] = $val;
                }
                $data = $this->getPovertyprojects($projectWhere, $limit, $layoutType);
                break;
            case 18:
                // 扶贫政策
                $where['type'] = 'policy';
                $data = $this->getArticles($where, $limit, $layoutType);
                break;
            case 19:
                // 一村一品
                $data = $this->getProducts($where, $limit, $layoutType);
                break;
            /*case 20:
                // 动态
                $data = $this->getCommunitydynamics($where, $limit, $this->userId);
                break;*/
            case 21:
                // 便民服务
                $where['type'] = 'work';
                $data = $this->getArticles($where, $limit, $layoutType);
                break;
            default: break;
        }

        return $data;
    }


    /**
     * 获取文章（通用）
     */
    protected function getArticles($where, $limit, $layoutType = '')
    {
        //$model = new Article;
        $model = db('article');
        $field = 'id, title as name, iconUrl as imgUrl, createDate';
        $result = $model->where($where)->field($field)->order('createDate DESC')->limit(0, $limit)->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取村子
     */
    protected function getVillages($where, $limit, $layoutType = '')
    {
        $model = new Villages();
        $field = 'id, name, imgUrl';
        $result = $model->where($where)->field($field)->limit(0, $limit)->order('sorting ASC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取村民
     */
    protected function getMembers($where, $limit)
    {
        $model = new Member();
        $field = 'id, name, avatar';
        $result = $model->where($where)->field($field)->limit(0, $limit)->order('sorting ASC')->select();
        if (!$result) {
            return [];
        }

        return $result;
    }

    /**
     * 获取乡镇机关
     */
    public function getInstitutions($where, $limit, $layoutType = ''){
        $model = db('institution');
        $field = 'id, name, imgUrl, createDate';
        $result = $model->where($where)->field($field)->limit(0, $limit)->order('createDate DESC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取农事知识
     */
    protected function getFarmings($where, $limit, $layoutType = '')
    {
        $field = 'id, title as name, imgUrl, createDate';
        $result = \app\admin\model\Knowledge::field($field)->limit(0, $limit)->order('topTime DESC,createDate DESC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取本地特色
     */
    protected function getSpecialtopics($where, $limit, $layoutType = '')
    {
        $field = 'id, title as name, imgUrl';
        $result = \app\admin\model\Specialtopic::where($where)->field($field)->limit(0, $limit)->order('sorting ASC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取特色专题
     */
    protected function getFeatures($where, $limit, $layoutType = '')
    {
        $field = 'id, name, imgUrl';
        $result = \app\admin\model\Featurecolumn::where($where)->field($field)->limit(0, $limit)->order('sorting ASC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取微课堂
     */
    public function getMicroclassrooms($where, $limit, $layoutType = ''){
        $model = db('microclassroom');
        $field = 'id, title as name, categoryId, imgUrl, createDate';
        $result = $model->where($where)->field($field)->limit(0, $limit)->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取在线考试
     */
    public function getOnlineexams($where, $limit, $layoutType = ''){
        $model = db('onlineexam');
        $field = 'id, name, startTime, endTime';
        $result = $model->where($where)->field($field)->limit(0, $limit)->order('startTime DESC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取会议
     */
    public function getMeetings($where, $limit, $layoutType = ''){
        $model = db('meeting');
        $field = 'id, title as name, startTime, endTime, address, createOper, status';
        $result = $model->where($where)->field($field)->limit(0, $limit)->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取调研
     */
    public function getResearchs($where, $limit, $layoutType = ''){
        $model = db('research');
        $where['isDelete'] = 2;
        $field = 'id, name, endTime, imgUrl';
        $result = $model->where($where)->field($field)->limit(0, $limit)->order('createDate DESC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取近期活动
     */
    public function getActivity($where, $limit, $layoutType = ''){
        //$model = new Activity();
        $model = db('activity');
        $where['isDelete'] = 2;
        $where['endTime'] = ['egt', time()];
        $field = 'id, title, imgUrl, startTime, endTime, deadline, createOper, sponsor';
        $result = $model->where($where)->field($field)->limit(0, $limit)->order('startTime ASC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $item['name'] = $item['title'];
            $memberId = Operator::where(['id' => $item['createOper']])->value('memberId');
            if($memberId && $memberId != 0){
                // 组织
                $organization = Member::alias('a')->where(['a.id' => $memberId])->join('__ORGANIZATION__ o', 'a.organizationId = o.id')->value('o.name');
                $item['organization'] = $organization;
            }else{
                $item['organization'] = $this->defaultOrganization;
            }
            unset($item['createOper']);

            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取扶贫项目
     */
    public function getPovertyprojects($where, $limit, $layoutType = '')
    {
        $where['a.isDelete'] = 2;
        $model = new Povertyproject();
        $field = 'a.id, a.title, a.imgUrl, a.type, a.productName, a.productNum, a.money';
        $result = $model->alias('a')->where($where)->join('member b','a.povertymemberId = b.id')->field($field)->limit(0, $limit)->order('a.createDate DESC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $item['name'] = $item['title'];

            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取产品
     */
    public function getProducts($where, $limit, $layoutType = '')
    {
        $model = new Product();
        $field = 'id, title, imgUrl, price, unit';
        $result = $model->where($where)->field($field)->limit(0, $limit)->order('createDate DESC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            $item['name'] = $item['title'];

            $config = [
                'layoutType' => isset($layoutType) ? $layoutType : 1,
                'shape' => 1
            ];
            $item['imgUrl'] = $this->getCuttingImg($item['imgUrl'], $config);
        }

        return $result;
    }

    /**
     * 获取最新动态
     */
    public function getCommunitydynamics($where, $limit, $userId)
    {
        $townId = $where['townId'];
        // 动态是否需要审核
        $config = $this->getTownConfig($townId);
        if(isset($config['dongtaicheckoff']) && $config['dongtaicheckoff'] == 1){
            $where['isPass'] = 1;
        }

        //$model = new Communitydynamics();
        $model = db('communitydynamics');
        $field = 'id, content, createUser as userId, createDate, countComment, countLike';
        $result = $model->where($where)->field($field)->limit(0, $limit)->order('createDate DESC')->select();
        if (!$result) {
            return false;
        }
        $result = DynamicService::formatDynamicList($result, $userId);

        return $result;
    }

}